package com.ruoyi.feike.controller;


import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.file.AsposeUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.feike.domain.BasicContract;
import com.ruoyi.feike.domain.vo.ContractRecord;
import com.ruoyi.feike.service.IBasicContractService;
import com.ruoyi.feike.service.IContractRecordSerivce;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static javax.jws.WebParam.Mode.OUT;


@Slf4j
@RestController
public class AbingController implements  ApplicationContextAware {

    @Value("${spring.mail.from}") // 从application.yml配置文件中获取
    private String from; //  发送发邮箱地址

    private static ApplicationContext context = null;


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private IContractRecordSerivce contractRecordSerivce;

    @Autowired
    private IBasicContractService basicContractService;

    @Autowired
    private RuntimeService runtimeService;

    @Resource
    private TaskService taskService;

    public static void main(String[] args) {
        List<String> everyday = DayUtils.getEveryday("2024-03-07", "2024-03-07");
        System.out.println(everyday);
    }




    @GetMapping("/abing")
    public void test(MultipartFile file) throws Exception {
       List<File> list = getFileList("D:\\ruoyi\\DDD\\20230328\\阿克苏汇尚汽车销售有限公司", true);
        System.out.println(list.size());

       // sendMailByEmailInfo("844132350@qq.com",null,true);
/*        ContractRecord contractRecord = new ContractRecord();
        List<ContractRecord> contractRecords = contractRecordSerivce.selectContractRecordList(contractRecord);
        for (ContractRecord record : contractRecords) {
            if(record.getDeposit().contains(".") && !record.getDeposit().contains("%") ){
                //说明是小数
                System.out.println(record.getDeposit());
                NumberFormat percentInstance = NumberFormat.getPercentInstance();
                percentInstance.setMaximumFractionDigits(2);
                String format = percentInstance.format(Double.valueOf(record.getDeposit()));
                System.out.println("改变后的值为   ："+format);
                record.setDeposit(format);
                contractRecordSerivce.updateContractRecord(record);
            }
        }*/


       /* ArrayList<String> list1 = new ArrayList<>();
        ArrayList<String> list2 = new ArrayList<>();
        list1.add("A89804");
        list1.add("K89802");
        list2.add("M02104");
        list2.add("R02104");
        ArrayList<List<String>> param = new ArrayList<>();
        param.add(list1);
        param.add(list2);
        HashMap<String,ArrayList<List<String>>> req = new HashMap<>();
        req.put("DealerCode",param);
        String url = OutRequest.CREDIT_URL;
        //post参数格式： {"DealerCode":[["A89804","K89802"],["M02104","R02104"]]}
        ResponseEntity<String> res = restTemplate.postForEntity(url,req,String.class);
        JSONObject parse = JSONObject.parseObject(res.getBody());
        Integer code = Integer.valueOf(parse.get("Code").toString());
        log.info("当前返回状态码为:{}",code);
        log.info("返回消息为:{}",parse.get("Message"));

        log.info("======="+parse.get("Data"));
        ThirdCreditInfoVO data = JSON.parseObject(parse.toString(), ThirdCreditInfoVO.class);
        log.info("当前实体对象：{}",data);
        return data;*/
//        BasicContract basicContract = new BasicContract();
//        basicContract.setSector("DS");
//        List<BasicContract> basicContracts = basicContractService.selectBasicContractList(basicContract);
//        Map<String, Map<String, List<BasicContract>>> collect = basicContracts.stream().collect(Collectors.groupingBy(BasicContract::getSector, Collectors.groupingBy(BasicContract::getLimittype)));
//        for (String key : collect.keySet()) {
//            System.out.println("key= "+ key + " and value= " + collect.get(key));
//            Map<String, List<BasicContract>> stringListMap = collect.get(key);
//            for (String key2 : stringListMap.keySet()) {
//                ArrayList<String> strings = new ArrayList<>();
//                strings.add(key);
//                strings.add(key2);
//                System.out.println(strings);
//                System.out.println("key2= "+ key + " and value2= " + collect.get(key));
//            }
//        }
//        List<Object> ObjList = new ArrayList<Object>();
//        HashMap<String, Object> map = new HashMap<>();
//        HashMap<String, Object> CreditLimit = new HashMap<>();
//        HashMap<String, Object> creditDetailsMap = new HashMap<>();
//        List<Object> creditDetailsList = new ArrayList<Object>();
//        CreditLimit.put("DealerCode","D02301");
//        CreditLimit.put("DistributorCode","000012");
//        CreditLimit.put("ExpiryDate","2024/07/02");
//        creditDetailsMap.put("Sector","Naveco Daily");
//        creditDetailsMap.put("LimitType","CB");
//        creditDetailsMap.put("CreditLimit","2000000");
//        creditDetailsList.add(creditDetailsMap);
//        CreditLimit.put("CreditDetails",creditDetailsList);
//        ObjList.add(CreditLimit);
//        map.put("CreditLimit",ObjList);
//        JSONObject jsonObject = new JSONObject(map);
//        System.out.println(jsonObject.toJSONString());
//        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//        HttpPost httpPost = new HttpPost("http://10.226.186.86:8081/CreditLimitAPIUAT7/CreditLimit/");
//        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
//        StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
//        entity.setContentType("application/json;charset=UTF-8");
//        entity.setContentEncoding("UTF-8");
//        httpPost.setEntity(entity);
//        httpPost.setHeader("Accept", "application/json, text/plain, */*");
//        httpPost.setHeader("Accept-Encoding", "gzip, deflate");
//        httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
//        httpPost.setHeader("Connection", "keep-alive");
//        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.38");
//        try {
//            StringBuffer resp = new StringBuffer();
//            if(StringUtils.isNotEmpty(resp)){
//                System.out.println("NOkong");
//            }else {
//                System.out.println("kong");
//            }
//            HttpResponse response = httpClient.execute(httpPost);
//            String responseStr = EntityUtils.toString(response.getEntity());
//            log.info("WFS外部接口数据返回结果=[{}]", responseStr);
//            JSONArray jsonArray = new JSONArray(Collections.singletonList(responseStr));
//            for (Object o : jsonArray) {
//                Map<String, Object> respMap = JSON.parseObject((String) o,Map.class);
//                Object creditLimit = respMap.get("CreditLimit");
//                JSONArray CreditLimitList = new JSONArray(Collections.singletonList(creditLimit));
//                for (Object o1 : CreditLimitList) {
//                    System.out.println(o1);
//                    List<Map<String, Object>> CreditLimitMap = (List<Map<String, Object>>) o1;
//                    for (Map<String, Object> stringObjectMap : CreditLimitMap) {
//                        System.out.println(stringObjectMap);
//                        List<Map<String, Object>> CreditDetails = (List<Map<String, Object>>) stringObjectMap.get("CreditDetails");
//                        for (Map<String, Object> creditDetail : CreditDetails) {
//                            Object Sector = creditDetail.get("Sector");
//                            Object LimitType = creditDetail.get("LimitType");
//                            Object Limit = creditDetail.get("CreditLimit");
//                            String Code = (String) creditDetail.get("Code");
//                            Object Message = creditDetail.get("Message");
//                            System.out.println(creditDetail);
//                            if(!Code.equals("000")){
//                                resp.append("额度类型 "+LimitType+"激活失败:"+Message).append("; ");
//                            }
//                        }
//                    }
//                }
//            }
//            if(StringUtils.isNotEmpty(resp)){
//                System.out.println("NOkong1");
//            }else {
//                System.out.println("kong1");
//            }
//            System.out.println(resp.toString());
//        }catch (Exception e){
//            e.printStackTrace();
//        }

    }






    @GetMapping("/abing1")
    public void exportShowPic(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String zipName = "myfile.zip";
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Content-Disposition","attachment; filename="+zipName);
        ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
        try {

            AbingController.doCompress("E:\\testExport\\export", out);
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            out.close();
        }
    }

   public void sendMailByEmailInfo(String sysUser,String businessKey,boolean flag) throws IOException {


        StringBuilder content = new StringBuilder("<html><head></head><body><h2>title</h2>");
        content.append("<table border=\"5\" style=\"border:solid 1px #E8F2F9;font-size=14px;;font-size:18px;\">");
        content.append("<tr style=\"background-color: #428BCA; color:#ffffff\"><th>Sector</th><th>Limit Type</th><th>column3</th></tr>");

            content.append("<tr>");
            content.append("<td>" + "1" + "</td>"); //第一列
            content.append("<td>" + "2" + "</td>"); //第二列
            content.append("<td>" + "3" + "</td>"); //第三列
            content.append("</tr>");

        content.append("</table>");
        content.append("<h3>description</h3>");
        content.append("</body></html>");


            //String content = "网站链接:"+url+"\n|--------|申请流程名称："+str+"\n|----------|经销商名称:"+names;
            String ln = "<br>";

            // 获取邮箱
            String email = sysUser;
            if (!StringUtil.isEmpty(email)) {
                try {
                    // 测试文本邮件发送（无附件）
                    String to = email;
                    String title = "您有待办任务请审批";

                    //带附件方式调用
                    new EmailUtil(from, mailSender).sendMessageCarryFiles(to, title, content.toString(), null);
                    // return AjaxResult.success();
                } catch (Exception e) {
                    log.error("邮件发送失败{}",e.getMessage());
                }
            }

    }



    public static List<String> getYearBetweenDate(String startTime, String endTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        // 声明保存日期集合
        List<String> list = new ArrayList<>();
        try {
            // 转化成日期类型
            Date startDate = sdf.parse(startTime);
            Date endDate = sdf.parse(endTime);

            //用Calendar 进行日期比较判断
            Calendar calendar = Calendar.getInstance();
            while (startDate.getTime() <= endDate.getTime()) {

                // 把日期添加到集合
                list.add(sdf.format(startDate));

                // 设置日期
                calendar.setTime(startDate);

                //把年数增加 1
                calendar.add(Calendar.YEAR, 1);

                // 获取增加后的日期
                startDate = calendar.getTime();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    private static void zipFile(List<File> fileList ,String zipPath) throws IOException {

        // 获取文件压缩包输出流
        try (OutputStream outputStream = new FileOutputStream(zipPath);
             CheckedOutputStream checkedOutputStream = new CheckedOutputStream(outputStream,new Adler32());
             ZipOutputStream zipOut = new ZipOutputStream(checkedOutputStream)){
            for (File file : fileList) {
                // 获取文件输入流
                InputStream fileIn = new FileInputStream(file);
                // 使用 common.io中的IOUtils获取文件字节数组
                byte[] bytes = IOUtils.toByteArray(fileIn);
                // 写入数据并刷新
                zipOut.putNextEntry(new ZipEntry(file.getName()));
                zipOut.write(bytes,0,bytes.length);
                zipOut.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    public static void compressToZip( List<File> files, String zipFilePath, String zipFilename) {
        File zipPath = new File(zipFilePath);
        if (!zipPath.exists()) {
            zipPath.mkdirs();
        }
        File zipFile = new File(zipPath + File.separator + zipFilename);
        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
            for (File f : files) {
                writeZip(f, "", zos);
            }
            //文件压缩完成后，删除被压缩文件
            // boolean flag = deleteDir(sourceFile);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }


    public static void writeZip(File file, String parentPath, ZipOutputStream zos) {
        if (file.isDirectory()) {
            //目录
            parentPath += file.getName() + File.separator;
            File[] files = file.listFiles();
            for (File f : files) {
                writeZip(f, parentPath, zos);
            }
        } else {
            //文件
            try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
                //指定zip文件夹
                ZipEntry zipEntry = new ZipEntry(parentPath + file.getName());
                zos.putNextEntry(zipEntry);
                int len;
                byte[] buffer = new byte[1024 * 10];
                while ((len = bis.read(buffer, 0, buffer.length)) != -1) {
                    zos.write(buffer, 0, len);
                    zos.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage(), e.getCause());
            }
        }
    }


    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        //删除空文件夹
        return dir.delete();
    }





    public static void doCompress(String srcFile, String zipFile) throws IOException {
        doCompress(new File(srcFile), new File(zipFile));
    }


    public static void doCompress(File srcFile, File zipFile) throws IOException {
        ZipOutputStream out = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(zipFile));
            doCompress(srcFile, out);
        } catch (Exception e) {
            throw e;
        } finally {
            out.close();//记得关闭资源
        }
    }

    public static void doCompress(String filelName, ZipOutputStream out) throws IOException{
        doCompress(new File(filelName), out);
    }

    public static void doCompress(File file, ZipOutputStream out) throws IOException{
        doCompress(file, out, "");
    }

    public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
        if ( inFile.isDirectory() ) {
            File[] files = inFile.listFiles();
            if (files!=null && files.length>0) {
                for (File file : files) {
                    String name = inFile.getName();
                    if (!"".equals(dir)) {
                        name = dir + "/" + name;
                    }
                    AbingController.doCompress(file, out, name);
                }
            }
        } else {
            AbingController.doZip(inFile, out, dir);
        }
    }

    public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
        String entryName = null;
        if (!"".equals(dir)) {
            entryName = dir + "/" + inFile.getName();
        } else {
            entryName = inFile.getName();
        }
        ZipEntry entry = new ZipEntry(entryName);
        out.putNextEntry(entry);

        int len = 0 ;
        byte[] buffer = new byte[1024];
        FileInputStream fis = new FileInputStream(inFile);
        while ((len = fis.read(buffer)) > 0) {
            out.write(buffer, 0, len);
            out.flush();
        }
        out.closeEntry();
        fis.close();
    }





    public  List<File> getFileList(String path, boolean isSortDesc) {
        List<File> list = getFileList(path);
        if (isSortDesc) {
            list.sort(Comparator.comparing(File::getAbsolutePath));
        } else {
            list.sort((f1, f2) -> f2.getAbsolutePath().compareTo(f1.getAbsolutePath()));
        }
        return list;
    }

    public  List<File> getFileList(String path) {
        List<File> rsList = new ArrayList<>();
        if (path == null || path.equals("")) {
            System.out.println("Error: path is blank.");
            return rsList;
        }
        File file = new File(path);
        if (!file.exists()) {
            System.out.println("Error: path is not existed.");
            return rsList;
        }
        // 处理文件
        if (file.isFile()) {
            System.out.println("Info: Only has a file.");
            rsList.add(file);
            return rsList;
        }
        // 处理文件夹
        if (null == file.listFiles()) {
            System.out.println("Info: Only has a empty directory.");
            rsList.add(file);
            return rsList;
        }
        int fileNum = 0;
        int folderNum = 0;
        LinkedList<File> forDealList = new LinkedList<>();
        forDealList.addAll(Arrays.asList(file.listFiles()));
        int m = 1;
        while (!forDealList.isEmpty()) {
            File firstFile = forDealList.removeFirst();
            if (firstFile.isFile()) {
                rsList.add(firstFile);
            }
        }

        if(rsList.size()==1){
            try {
                System.out.println("无需合并");
                String uuid = IdUtils.get16UUID();
                String newPath ="D:\\ruoyi\\OfflineContractByPeugeot\\"+ "/"+uuid+".pdf";
                String url = "\\splicepdf\\Peugeot1\\" + uuid + ".pdf"; 	//复制到的指定文件
                copy1(rsList.get(0).getPath().length(),rsList.get(0).getPath(),newPath);
            }catch (Exception e){
                e.printStackTrace();
            }

        }else if(rsList.size()>1){
            try {
                String uuid1 = IdUtils.get16UUID();
                String dizhi ="D:\\ruoyi\\OfflineContractByPeugeot\\"+ "/"+uuid1+".pdf";
                String url = "\\splicepdf\\Peugeot\\" + uuid1 + ".pdf";
                File f = AsposeUtil.MulFileToOne(rsList, dizhi);

            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            System.out.println("没有文件");
        }

        System.out.println("结束");
        return rsList;
    }

    private  void copyFileUsingFileStreams(String fileName, String newFileName)
            throws IOException {
        // 创建流对象
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        List<String> list = new ArrayList<>();
        String line = null;
        while ((line = br.readLine()) != null) {
            list.add(line);
        }

        int success = 0;
        int fail = 0;
        String startPath;
        String endPath;
        startPath = "startPath";
        endPath = "D:\\ruoyi\\uploadPath\\splicepdf\\Peugeot\\";
        File tmpFile = new File(endPath);//获取文件夹路径
        if (!tmpFile.exists()) {//判断文件夹是否创建，没有创建则创建新文件夹
            tmpFile.mkdirs();
        }
        File startFile = new File(fileName);
        try {
            if (startFile.renameTo(new File(newFileName))) {
                System.out.println("成功");
            } else {
                System.out.println("失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public  void copy1(int oldLength,String oldPath, String newPath) throws IOException {
        File f1 = new File(oldPath);
        File f2 = new File(newPath+oldPath.substring(oldLength));

        //如果f1为空 直接退出
        if (!f1.exists())
            return;

        if (f1.isDirectory()) {
            //目标目录不存在此文件夹就进行新建
            if (!f2.exists())
                f2.mkdirs();

            File[] f1s = f1.listFiles();
            if (f1s != null) {
                for (File file : f1s) {
                    copy1(oldLength, file.getPath(), newPath);
                }
            }
        } else {
            //如果是文件的话就进行复制
            f2.delete();    //如果存在存量数据就先删除
            Files.copy(f1.toPath(), f2.toPath());
        }
    }

    public  static List<Map<String,String>> getCycleList(int cycleNum,String startTime,String endTime) throws ParseException {
        System.out.println("统计的时间段为：从"+startTime+"到"+endTime);
        Date endParse = new SimpleDateFormat("yyyy-MM-dd").parse(endTime);
        Long endLong = endParse.getTime();

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//这个是你要转成后的时间的格式
        endTime = sdf.format(new Date(endLong));
        System.out.println("结束时间是："+endTime);
        int daysBetweenNum = daysBetween(startTime, endTime);
        int cycleForNum = daysBetweenNum % cycleNum == 0 ? (daysBetweenNum / cycleNum) : (daysBetweenNum / cycleNum) + 1;
        System.out.println("两日期间相隔的天数为：" + daysBetweenNum);
        System.out.println("周期选择是：" + cycleNum + "天一周期, 则切割出来的周期存在个数：" + cycleForNum);
        Date startParse = new SimpleDateFormat("yyyy-MM-dd").parse(startTime);
        Long startLong = startParse.getTime();
        Long calculationLong = endLong;
        List<Map<String,String>> CycleTimeList=new ArrayList();
        for (int i = 1; i <= cycleForNum; i++) {
            String endStr = sdf.format(new Date(calculationLong));
            System.out.println(endStr);
            Date endStrParse = new SimpleDateFormat("yyyy-MM-dd").parse(endStr);
            Long endStrLong = endStrParse.getTime();
            Long cycleLong = cycleNum*86400000l;
            calculationLong = endStrLong - cycleLong;
            String format = sdf.format(new Date(calculationLong));
            System.out.println(format);
            String startStr = startTime;
            if (calculationLong >= startLong) {
                startStr = sdf.format(new Date(calculationLong));
            }
            calculationLong = calculationLong-86400000l;
            System.out.println("起始:" + startStr + "结束：" + endStr);
            HashMap<String, String> stringStringHashMap = new HashMap<>();
            stringStringHashMap.put("startStr",startStr);
            stringStringHashMap.put("endStr",endStr);
            stringStringHashMap.put("stor",String.valueOf(i));
            CycleTimeList.add(stringStringHashMap);
        }
        Collections.sort(CycleTimeList, new Comparator<Map<String,String>>() {
            @Override
            public int compare(Map<String,String> o1, Map<String,String> o2) {
                return o2.get("stor").compareTo(o1.get("stor"));
            }

            @Override
            public boolean equals(Object obj) {
                return false;
            }
        });
        System.out.println("周期list："+CycleTimeList.toString());
        return CycleTimeList;
    }

    public static int daysBetween(String smdate, String bdate) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}
